<template>
  <el-card class="cart">
    <h2>购物车</h2>
    <el-button type="primary" @click="fetchCart">刷新购物车</el-button>
    <el-table :data="items" style="width: 100%; margin-top: 20px;">
      <el-table-column prop="user_card_id" label="商品ID" width="120" />
      <el-table-column prop="quantity" label="数量" width="100" />
      <el-table-column label="操作" width="120">
        <template #default="scope">
          <el-button size="small" type="primary" @click="createOrder(scope.row)">下单</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-empty v-if="items.length === 0" description="购物车为空" />
    <el-alert v-if="msg" :title="msg" type="info" show-icon class="msg-alert" />
  </el-card>
</template>

<script setup>
import { ref } from 'vue'
import axios from 'axios'
import { ElMessage } from 'element-plus'

const items = ref([])
const msg = ref('')

const fetchCart = async () => {
  try {
    const res = await axios.get('/order/cart/1')
    items.value = res.data
    msg.value = ''
  } catch (e) {
    msg.value = e.response?.data?.detail || '查询失败'
    ElMessage.error(msg.value)
  }
}
const createOrder = async (item) => {
  try {
    await axios.post('/order/create', { user_card_id: item.user_card_id, quantity: item.quantity }, { params: { buyer_id: 1 } })
    msg.value = '下单成功'
    ElMessage.success(msg.value)
  } catch (e) {
    msg.value = e.response?.data?.detail || '下单失败'
    ElMessage.error(msg.value)
  }
}
</script>

<style scoped>
.cart {
  max-width: 700px;
  margin: 40px auto;
  padding: 32px 24px;
  border-radius: 12px;
  background: #f8f9fa;
}
.msg-alert {
  margin-top: 16px;
}
</style> 